<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <h2>登录</h2>
      </template>
      <el-form :model="loginForm" :rules="rules" ref="loginForm" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" @keyup.enter="handleLogin"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" :loading="loading">登录</el-button>
          <el-button @click="$router.push('/register')">注册账号</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { userApi } from '@/api/user'
import { ElMessage } from 'element-plus'

export default {
  name: 'LoginPage',
  emits: ['login-success'],
  data() {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      loading: false,
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async handleLogin() {
      try {
        await this.$refs.loginForm.validate()
        this.loading = true
        const response = await userApi.login(this.loginForm)
        
        if (!response || !response.token || !response.userId) {
          throw new Error('登录响应格式错误')
        }
        
        // 存储用户信息和token
        localStorage.setItem('token', response.token)
        localStorage.setItem('userId', response.userId)
        localStorage.setItem('username', response.username)
        
        // 触发登录成功事件
        this.$emit('login-success')
        
        // 跳转到首页
        this.$router.push('/')
        ElMessage.success('登录成功')
      } catch (error) {
        console.error('登录失败:', error)
        if (error.response?.data?.message) {
          ElMessage.error(error.response.data.message)
        } else if (error.message === '登录响应格式错误') {
          ElMessage.error('服务器响应格式错误，请联系管理员')
        } else {
          ElMessage.error('登录失败，请检查用户名和密码是否正确')
        }
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 80vh;
}

.login-card {
  width: 400px;
}
</style> 